# 这个是用生成的模型对原始训练集进行测试，比较测试结果与原始真是数据结果的匹配度来判断精确度
import numpy as np
import pandas as pd
import tensorflow
from keras_preprocessing.image import ImageDataGenerator
from matplotlib import pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score, confusion_matrix, ConfusionMatrixDisplay
from sklearn.preprocessing import LabelEncoder
from tensorflow.core.protobuf.config_pb2 import ConfigProto
from tensorflow.python.client.session import Session
from tensorflow.python.keras.models import load_model

config = ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.5  #占用85%显存
session = Session(config=config)

data = pd.read_csv('input/paddy-disease-classification/train.csv')
data =data.values
# print(data)
# 需要预测的数据
y_test = data[0:10408,1]
# print(y_test)

# 转化标签
le = LabelEncoder()
y_test = le.fit_transform(y_test)
print(y_test)
print(y_test.shape) # 10406

model = load_model('D:\PyCharm_workplace\Test\saved_model\my_model03.h5')

img_rows, img_cols = 256, 256
batch_size = 100
train_loc = 'input/paddy-disease-classification/train_images/'
test_data = ImageDataGenerator(rescale=1.0/255).flow_from_directory(
    directory=train_loc,
    target_size=(img_rows, img_cols),
    batch_size=batch_size,
    classes=['.'],
    shuffle=False,
)

y_pred = model.predict(test_data)
print(y_pred)
print(y_pred.shape)
# np.argmax()是numpy中获取array的某一个维度中数值最大的那个元素的索引
# axis=1指定代表我要查找的最大元素在第1维中的索引值
y_predict_max = np.argmax(y_pred,axis=1)    # 转换为预测标签


acc = tensorflow.keras.metrics.SparseCategoricalAccuracy()(y_test,y_pred)
print('准确率：')
print(acc)
print('测试集的准确率Accuracy：', accuracy_score(y_test, y_predict_max))
print('精确度Precision:', precision_score(y_test, y_predict_max, average='micro'))
print('召回率Recall:', recall_score(y_test, y_predict_max, average='micro'))
# 混淆矩阵
cm = confusion_matrix(y_test,y_predict_max)
print(cm)
cm_display = ConfusionMatrixDisplay(cm).plot()
plt.show()
